package social;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class CreateUserServlet
 */
@WebServlet("/CreateUserServlet")
public class CreateUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreateUserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		SocialDBC db = (SocialDBC) getServletContext().getAttribute("database");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		HttpSession session = request.getSession();
		
		if (username.contains(" ") || username.contains("%") || username.contains("*")) {
			session.setAttribute("username", username);
			request.getRequestDispatcher("create-user.jsp").forward(request, response);
		} else {

			int result = db.addUser(username, password, "user");
			if (result==1) {
				//user already exists
				session.setAttribute("username", username);
				request.getRequestDispatcher("create-user.jsp").forward(request, response);
			} else {
				//login
				session.setAttribute("username", username);
				session.setAttribute("login", "true");
				session.setAttribute("friendList", db.getFriendList(username));
				//request.setAttribute("profileName", username);
				session.setAttribute("profileName", username);
				request.getRequestDispatcher("user-profile.jsp").forward(request, response);
			}
		}
	}

}
